package com.shizhanzhe.zxbapp.vip;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dpuntu.downloader.DownloadManager;
import com.dpuntu.downloader.Downloader;
import com.dpuntu.downloader.Observer;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.AppDetail;
import com.shizhanzhe.zxbapp.bean.GameDetail;
import com.shizhanzhe.zxbapp.bean.Gbean;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.home.AppDetailActivity;
import com.shizhanzhe.zxbapp.home.GamedetailAdapter;
import com.shizhanzhe.zxbapp.vip.GameDetailActivity;
import com.shizhanzhe.zxbapp.home.AppDetailAdapter;
import com.shizhanzhe.zxbapp.ui.LoginActivity;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.DownUtil;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.SharedPreferencesUtils;
import com.shizhanzhe.zxbapp.utils.Util;
import com.shizhanzhe.zxbapp.widget.MyListView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;

/**
 * Created by zz9527 on 2018/12/4.
 */
public class GameDetailActivity extends Activity implements View.OnClickListener {
    private ImageView appIcon;
    private TextView appName;
    private TextView total;
    private TextView vipdivide;
    private Button openOrDownloadBtn;
    private TextView gameuser;
    private ProgressBar downlaodProgressBar;

    private SmartRefreshLayout refresh; // 下拉刷新组件
    private MyListView listView;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private String packageName = "";
    private String baoming = "";
    private String taskId = "";
    private TextView intro;
    private TextView day;
    private String encode;
    private String idtask;
    private TabLayout tab;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gamedetail);
        ImmersionBar.with(this).statusBarColor(R.color.them)
                .init();
        File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ZXBFile");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        UserBean.uid = (int) SharedPreferencesUtils.getParam(this, "uid", 0);
        packageName = (String) SharedPreferencesUtils.getParam(getApplicationContext(), "packName", "");
        taskId = (String) SharedPreferencesUtils.getParam(this, "taskId", "");
        encode = getIntent().getStringExtra("sign");
        idtask = getIntent().getStringExtra("idtask");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
    }

    private void initView() {
        refresh = findViewById(R.id.refresh);
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                requestDetailData();
            }
        });
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tab = findViewById(R.id.tab);
        listView = findViewById(R.id.detailpage_listview);
        total = findViewById(R.id.tv_detailpage_total);
        gameuser = findViewById(R.id.game_user);
        vipdivide = findViewById(R.id.tv_detailpage_vip);
        appIcon = (ImageView) findViewById(R.id.iv_detailpage_appicon);
        appName = (TextView) findViewById(R.id.tv_detailpage_appname);
        intro = (TextView) findViewById(R.id.intro);
        day = findViewById(R.id.tv_day);
        final TagFlowLayout flowlayout = findViewById(R.id.flowlayout);
        flowlayout.setAdapter(new TagAdapter<String>(getIntent().getStringArrayListExtra("bq")) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(GameDetailActivity.this).inflate(R.layout.tv,
                        flowlayout, false);
                tv.setText(s);
                return tv;
            }
        });
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        downlaodProgressBar = (ProgressBar) findViewById(R.id.pb_download);
        downlaodProgressBar.setVisibility(View.GONE);
        openOrDownloadBtn = (Button) findViewById(R.id.btn_detailpage_open_or_install);
        openOrDownloadBtn.setOnClickListener(this);

        DownloadManager.subjectTask(idtask, new DownloadObserver(downlaodProgressBar, openOrDownloadBtn));
        requestDetailData();
    }

    GameDetail.DataBean data;

    private void requestDetailData() {

        OkHttpDownloadJsonUtil.downloadJson(this, Path.GAMEDETAIL(Util.getIMEI(this), UserBean.uid, encode, idtask), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {


            @Override
            public void onsendJson(final String json) {
                Log.i("______", Path.GAMEDETAIL(Util.getIMEI(GameDetailActivity.this), UserBean.uid, encode, idtask));
                try {


                    final Gson gson = new Gson();
                    data = gson.fromJson(json, GameDetail.class).getData();
                    List<GameDetail.DataBean.AccountInfoBean> accountInfo = data.getAccountInfo();
                    String str = "";
                    for (GameDetail.DataBean.AccountInfoBean b : accountInfo) {
                        str = str + b.getKey() + ":" + b.getVal() + "\n";
                    }
                    if ("".equals(str)) {
                        gameuser.setText(Html.fromHtml("<p class=\\\"tleft\\\">点击开始任务，下载或打开应用，注册帐号拿奖励吧<br/>注册完成后请<a href=\\\"javascript:window.location.reload();\\\" style=\\\"color:#E63528;\\\">点此刷新</a>核对注册帐号</p>"));
                    } else {
                        gameuser.setText(str);
                    }
                    if (UserBean.level > 0) {
                        total.setText("+" + Util.Sub(Double.parseDouble(data.getMtTaskFeeSum()) * 0.9 * (Double.parseDouble(UserBean.vipdivide) + Double.parseDouble(UserBean.divide)) + "") + "元");
                    } else {
                        total.setText("+" + Util.Sub(Double.parseDouble(data.getMtTaskFeeSum()) * 0.9 * Double.parseDouble(UserBean.divide) + "") + "元");
                    }
                    Glide.with(getApplicationContext()).load(data.getLogo()).apply(new RequestOptions().error(R.mipmap.logo)).into(appIcon);
                    appName.setText(data.getAppName());
                    if (UserBean.level > 0) {
                        total.setText("+" + Util.Sub(Double.parseDouble(data.getMtTaskFeeSum()) * 0.9 * (Double.parseDouble(UserBean.vipdivide) + Double.parseDouble(UserBean.divide)) + "") + "元");
                    } else {
                        total.setText("+" + Util.Sub(Double.parseDouble(data.getMtTaskFeeSum()) * 0.9 * Double.parseDouble(UserBean.divide) + "") + "元");
                    }
                    String introstr = "";
                    for (String s :
                            data.getRaiders()) {
                        introstr += s + "\n";
                    }
                    intro.setText(introstr);
                    day.setText("剩余" + data.getDays() + "天");
                    baoming = data.getCredentialID();
                    if (Util.isPackageExist(GameDetailActivity.this, baoming)) {
                        //已安装
                        openOrDownloadBtn.setText("打开");
                    } else if (packageName.contains("andriod" + idtask + ".apk")) {
                        //已下载，未安装
                        openOrDownloadBtn.setText("安装");
                    } else if (taskId.contains(idtask)) {
                        //继续下载
                        openOrDownloadBtn.setText("继续");
                    } else {
                        //下载
                        openOrDownloadBtn.setText("下载");
                    }
                    for (int i = 0; i < data.getSubTaskList().size(); i++) {
                        if (tab.getTabCount() == data.getSubTaskList().size()) {
                            return;
                        }
                        tab.addTab(tab.newTab().setText(data.getSubTaskList().get(i).getTitle()));
                    }
                    final List<Gbean> list = new ArrayList<>();
                    HashMap<String, Gbean> map = data.getSubTaskList().get(0).getList();
                    for (int k = 1; k < map.size() + 1; k++) {
                        if (map.get(k + "") != null) {
                            list.add(map.get(k + ""));
                        }
                    }
                    listView.setAdapter(new GamedetailAdapter(GameDetailActivity.this, list));
                    tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                        @Override
                        public void onTabSelected(TabLayout.Tab tab) {
                            final List<Gbean> list = new ArrayList<>();
                            HashMap<String, Gbean> map = data.getSubTaskList().get(tab.getPosition()).getList();
                            for (int k = 1; k < map.size() + 1; k++) {
                                if (map.get(k + "") != null) {
                                    list.add(map.get(k + ""));
                                }
                            }
                            if (list.size() == 0) {
                                return;
                            } else {
                                listView.setAdapter(new GamedetailAdapter(GameDetailActivity.this, list));
                            }
                        }

                        @Override
                        public void onTabUnselected(TabLayout.Tab tab) {

                        }

                        @Override
                        public void onTabReselected(TabLayout.Tab tab) {

                        }
                    });
//                rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//                    @Override
//                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
//                        final List<Gbean> list = new ArrayList<>();
//                        HashMap<String, Gbean> map = data.getSubTaskList().get(i).getList();
//                        for (int k = 1; k < map.size() + 1; k++) {
//                            list.add(map.get(k + ""));
//                        }
//                        listView.setAdapter(new GamedetailAdapter(GameDetailActivity.this, list));
//                    }
//                });
                } catch (Exception e) {
                    Toast.makeText(GameDetailActivity.this, "此游戏数据异常", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_detailpage_open_or_install:
                if (UserBean.uid == 0) {
                    startActivity(new Intent(GameDetailActivity.this, LoginActivity.class));
                } else {
                    switch (openOrDownloadBtn.getText().toString()) {
                        case "下载":
                            down();
                            break;
                        case "安装":
                            File savedFile = new File(Environment.getExternalStorageDirectory().toString()
                                    + "/ZXBFile/andriod" + idtask + ".apk");
                            if (savedFile.exists()) {
                                DownUtil.installAPK(this, savedFile);
                            } else {
                                down();
                            }
                            break;
                        case "打开":
                            DownUtil.openApp(this, baoming);
                            break;
                        case "继续":
                            DownloadManager.start(idtask);
                            break;
                        default:
                            //下载中，暂停
                            DownloadManager.pause(idtask);
                            break;
                    }
                    DownloadManager.subjectTask(idtask, new DownloadObserver(downlaodProgressBar, openOrDownloadBtn));
                    break;
                }

                break;

            default:
                break;
        }
    }


    //下载
    private void down() {
//        Log.i("__________", data.getUrlDownload());
        try {
            List<Downloader> downloaders = new ArrayList<Downloader>();
            OkHttpClient client = new OkHttpClient.Builder().build();
            Downloader downloader = new Downloader.Builder()
                    .client(client)
                    .fileName("andriod" + idtask + ".apk")
                    .filePath(Environment.getExternalStorageDirectory().getPath() + "/ZXBFile")
                    .taskId(idtask)
                    .url(data.getUrlDownload())
                    .build();
            downloaders.add(downloader);
            DownloadManager.addDownloader(downloaders);
            DownloadManager.start(idtask);
            if (null == taskId | !taskId.contains(idtask)) {
                if (taskId.equals("")) {
                    SharedPreferencesUtils.setParam(this, "taskId", idtask);
                } else {
                    SharedPreferencesUtils.setParam(this, "taskId", taskId + ";" + idtask);
                }
            }
        } catch (Exception e) {
        }
    }

    private class DownloadObserver implements Observer {
        private ProgressBar mTextView;
        private TextView textView;

        public DownloadObserver(ProgressBar textView, TextView textView1) {
            mTextView = textView;
            this.textView = textView1;
        }

        @Override
        public void onCreate(String s) {

        }

        @Override
        public void onReady(String s) {

        }

        @Override
        public void onLoading(String s, final String s1, final long l, final long l1) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setVisibility(View.VISIBLE);
                    mTextView.setProgress((int) (((double) l1 / (double) l) * 100));
                    textView.setText((String.format("正在下载,已完成%d%% ,下载速度: %s", (int) (((double) l1 / (double) l) * 100), s1)));
                }
            });
        }

        @Override
        public void onPause(String s, final long l, final long l1) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setProgress((int) (((double) l1 / (double) l) * 100));
                    textView.setText("继续");
                }
            });
        }

        @Override
        public void onFinish(String s) {
            DownloadManager.removeTaskObserver(s, this);
            // 最好不要在这里做这一步操作，因为你可能绑定了其他监听者，有一处移除，其他的均无法监听甚至出现异常
            //  DownloadManager.remove(taskId);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setProgress(100);
                    mTextView.setVisibility(View.GONE);
                    textView.setText("安装");
                    File file = new File(Environment.getExternalStorageDirectory().toString()
                            + "/ZXBFile/andriod" + idtask + ".apk");
                    SharedPreferencesUtils.setParam(getApplicationContext(), "packName", packageName + "andriod" + idtask + ".apk");
                    DownUtil.installAPK(getApplicationContext(), file);
                }
            });
        }

        @Override
        public void onError(String s, String s1, long l, long l1) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "下载异常", Toast.LENGTH_SHORT).show();
                    textView.setText("下载");
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }
}
